package com.fly.caihong.activity;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.fly.caihong.R;
import com.fly.caihong.base.BaseActivity;
import com.fly.caihong.model.LUser;
import com.fly.caihong.utils.ActivityUtils;
import com.fly.caihong.utils.KeyboardUtils;
import com.fly.caihong.utils.SPUtils;
import com.fly.caihong.utils.ToastUtils;

import org.litepal.crud.DataSupport;

public class LoginActivity extends BaseActivity {

    private EditText mEdtName, mEdtPwd;
    private Button mBtnLogin;
    private TextView mTvRegister;

    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mToolbar.setMainTitle("登录");
        mEdtName = findViewById(R.id.edt_name);
        mEdtPwd = findViewById(R.id.edt_pwd);
        mBtnLogin = findViewById(R.id.btn_login);
        mTvRegister = findViewById(R.id.tv_register);
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEdtName.getText().toString().equals("")) {
                    ToastUtils.showLong("请输入用户名");
                    return;
                }
                if (mEdtPwd.getText().toString().equals("")) {
                    ToastUtils.showLong("请输入密码");
                    return;
                }
                KeyboardUtils.hideSoftInput(LoginActivity.this);
                showLoading("正在登录,请稍候...");
                mBtnLogin.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoading();
                        boolean userExist = DataSupport.isExist(LUser.class
                                , "userName=? and password=?", mEdtName.getText().toString()
                                , mEdtPwd.getText().toString());
                        if (!userExist) {
                            ToastUtils.showLong("用户名或密码错误");
                            return;
                        }
                        ToastUtils.showLong("登录成功");
                        SPUtils.getInstance().put("userName", mEdtName.getText().toString());
                        finish();
                    }
                }, 2000);

            }
        });
        mTvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.startActivity(LoginActivity.this, RegisterActivity.class);
            }
        });
    }

}
